package com.atguigu.bookcity.controller;

import com.atguigu.bookcity.entity.Book;
import com.atguigu.bookcity.service.BookService;
import com.atguigu.bookcity.service.ExcelService;
import com.atguigu.bookcity.vo.CommonResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gaoice.easyexcel.spring.boot.autoconfigure.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@CrossOrigin
@Controller
@Api(tags = "excel服务")
@RequestMapping("/bookcity/book/excel")
public class ExcelController {

    @Resource
    private BookService bookService;

    @Resource
    private ExcelService excelService;

    /**
     *
     * controller
     * 若是使用RestController注解,Excel下载会失效
     * @param nameCondition 书名
     * @param from  价格区间
     * @param to    价格区间
     *
     */
    @ApiOperation(
            value = "excel按价格区间条件和模糊书名下载图书Excel",
            notes = "admin权限",
            produces = "application/json")
    @RequiresRoles("admin")
    @GetMapping("/download")
    @ResponseExcel(value = {
            "id", "bookName", "cover",
            "price", "author", "press",
            "publishingTime", "printingTime"})
    public List<Book> list(@RequestParam(required = false) String nameCondition,
                           @RequestParam(required = false) BigDecimal from,
                           @RequestParam(required = false) BigDecimal to) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        if (nameCondition != null) {
            wrapper.like("book_name", nameCondition);
        }

        if (from != null && to != null)
            wrapper.between("price", from, to);
        return bookService.list(wrapper);
    }

    @ApiOperation(
            value = "上传Excel",
            notes = "admin权限",
            produces = "application/json")
    @ResponseBody
    @PostMapping("/uploadbooks")
    @RequiresRoles("admin")
    public CommonResult uploadBooks(MultipartFile file) {
        return excelService.uploadBooks(file, bookService);
    }
}
